/**
 * Copyright 2007-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.asemantics.anthill;

import org.apache.tools.ant.BuildException;
import org.jivesoftware.smack.packet.Message;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.Map;

/**
 * This class extends {@link org.jivesoftware.smack.packet.Message}
 * to contain the results of a command execution. 
 *
 * @author Michele Mostarda
 */
public abstract class CommandResponseMessage extends BaseMessage {

    /**
     * The class name of the response.
     */
    public static final String COMMAND_RESPONSE_TYPE = "command_result_type";

    /**
     * The defualt command message body.
     */
    public static final String MESSAGE_BODY      = "anthill_command_response_message";

    /**
     * The name of the message property containing the exception message, if any.
     */
    public static final String EXCEPTION_MESSAGE_PROPERTY = "exception_message";

    /**
     * The name of the message property containing the exception object, if any.
     */
    public static final String EXCEPTION_PROPERTY = "exception_body";

    /**
     * Constructor.
     * Neither result parameters nor exceptions are returned.
     *
     * @param remoteOperation the remote operation who generated this reponse message.
     */
    private CommandResponseMessage(Class<? extends RemoteOperation> remoteOperation) {
        super(remoteOperation);

        String objectType = this.getClass().getName();
        setProperty(COMMAND_RESPONSE_TYPE, objectType);
        setBody(MESSAGE_BODY);
    }

    /**
     * Constructor.
     *
     * @param t the returned exception.
     * @param remoteOperation the remote operation who generated this reponse message.
     */
    public CommandResponseMessage(Class<? extends RemoteOperation> remoteOperation, Throwable t) {
        this(remoteOperation);

        if(t == null) { return; }
        setProperty(EXCEPTION_MESSAGE_PROPERTY, t.getMessage());
        setProperty(EXCEPTION_PROPERTY, t);
        setBody(null);
        setBody( "ERROR: " + t.getMessage() );
    }

    /**
     * Constructor.
     *
     * @param remoteOperation the operation generating this response.
     * @param returnProperties the protperties to be returned.
     * @param boxing if <code>true</code> the command response prepared to box parameters (server side),
     *  otherwise it is used to unbox parameters (client side).
     */
    public CommandResponseMessage(
            Class<? extends RemoteOperation> remoteOperation,
            final Map<String,Object> returnProperties,
            boolean boxing
    ) {
        this(remoteOperation, null, returnProperties, boxing);
    }

    /**
     * Constructor.
     * Proides both exception and return parameters.
     *
     * @param remoteOperation the operation generating this response.
     * @param throwable exception raied during the execution of a command, can be <code>null</code>.
     * @param returnProperties a map containing propertyName / proptertyValue couples, can be <code>null</code>.
     * @param boxing if <code>true</code> the command response prepared to box parameters (server side),
     *  otherwise it is used to unbox parameters (client side).
     */
    //TODO: find better definition for BOXING flag.
    public CommandResponseMessage(
            Class <? extends RemoteOperation> remoteOperation,
            Throwable throwable,
            final Map<String,Object> returnProperties,
            boolean boxing
    ) {
        this(remoteOperation, throwable);

        if(returnProperties == null) {
            return;
        }

        for(Map.Entry<String, Object> entry : returnProperties.entrySet()) {
            setProperty(
                    ( boxing ? InvokeCommandMessage.PARAMETER_PREFIX : "" ) + entry.getKey(),
                    entry.getValue() != null ?  entry.getValue() : ""
            );
        }
    }

    protected CommandResponseMessage(Throwable throwable) {
        this(null, throwable);
    }

    /**
     * Returns <code>true</code> if the given message contains an exception, false otherwise.
     * <code>false</code> otherwise.
     *
     * @param message
     * @return
     * @throws IllegalArgumentException if the given message is not a <i>CommandResultMessage</i>.
     */
    public static boolean isExceptionRaised(Message message) {
        return message.getProperty(EXCEPTION_MESSAGE_PROPERTY) != null;
    }

    /**
     * Returns the exception message into the given message.
     *
     * @param message
     * @return
     * @throws IllegalArgumentException if the given message is not a <i>CommandResultMessage</i>.
     */
    public static String getExceptionMessage(Message message) {
        return (String) message.getProperty(EXCEPTION_MESSAGE_PROPERTY);
    }

    /**
     * Extractes the remote exception raised by the listener target invocation.
     *
     * @param message
     * @return the deserialized exception into the given message.
     * @throws IllegalArgumentException if the given message is not a <i>CommandResultMessage</i>.
     */
    public static RemoteException getRemoteException(Message message) {
        return new RemoteException(
                getExceptionMessage(message),
                (Throwable) message.getProperty(EXCEPTION_PROPERTY)
        );
    }

    /**
     * Takes a low level response message and converts it to a {@link CommandResponseMessage} object.
     *
     * @param message
     * @return
     */
    protected static CommandResponseMessage deserializeCommandMessage(Message message) {
        String className = (String) message.getProperty(COMMAND_RESPONSE_TYPE);
        System.out.println("COMMAND_RESPONSE TYPE: " + className);
        if(className == null) {
            throw new IllegalArgumentException("Expected CommandResponseMessage derived type");
        }

        ClassLoader classLoader = CommandMessage.class.getClassLoader();
        Class commandMessageClass;
        try {
            commandMessageClass = classLoader.loadClass(className);
            Constructor<CommandResponseMessage> constructor = commandMessageClass.getConstructor(Map.class);
            CommandResponseMessage commandMessage = constructor.newInstance(getMessageMap(message));
            return commandMessage;
        } catch (ClassNotFoundException e) {
            throw new BuildException("Cannot load class: "        + className, e);
        } catch (IllegalAccessException e) {
            throw new BuildException("Cannot access class: "      + className, e);
        } catch (InstantiationException e) {
            throw new BuildException("Cannot instantiate class: " + className, e);
        } catch (NoSuchMethodException e) {
            throw new BuildException("Cannot find constructor: "  + className, e);
        } catch (InvocationTargetException e) {
            if(e.getCause() != null) {
                System.err.println(e.getClass().getName() + " cause: ");
                e.getCause().printStackTrace();
            }
            throw new BuildException("Cannot invoke constructor");
        }
    }

}
